package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.common.utls.SessionUtils;
import com.example.mybatisplus.model.domain.User;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 *
 *  前端控制器
 *
 *
 * @author blue
 * @since 2021-12-29
 * @version v1.0
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger( UserController.class );

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public JsonResponse login(User user) {
        //先查这个用户
        User login = userService.login(user);
        //如果登录成功，则需要将当前用户存进session
        if (login != null) {
            //存进session
            SessionUtils.saveLoginUser(login);
        }
        return JsonResponse.success(login);
    }

    @PostMapping("/regist")
    public JsonResponse regist(@RequestBody User user) {
        JsonResponse jsonResponse =  userService.regist(user);
//        userService.save(user);
        //执行成功，直接给前端返回
        return jsonResponse;
    }

    @GetMapping("/list")
    public JsonResponse list(PageDTO page, User user) {
        //创建一个分页器
        Page<User> page1 = userService.listByPage(page, user);
        return JsonResponse.success(page1);
    }

    @GetMapping("/deleteById")
    public JsonResponse deleteById(Long id) {
        userService.removeById(id);
        return JsonResponse.success(true);
    }

    @PostMapping("/updateById")
    public JsonResponse updataById(@RequestBody User user) {
        userService.updateById(user);
        return JsonResponse.success(true);
    }
}

